<template>
  <div class="finance-management">
    <div class="page-header">
      <h2>财务管理</h2>
    </div>

    <!-- 财务概览卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6" v-for="(card, index) in statisticsCards" :key="index">
        <el-card class="statistics-card" :body-style="{ padding: '20px' }">
          <div class="card-content">
            <div class="icon-wrapper" :style="{ backgroundColor: card.color }">
              <i :class="card.icon"></i>
            </div>
            <div class="statistics-info">
              <div class="title">{{ card.title }}</div>
              <div class="value">{{ card.value }}</div>
              <div
                class="trend"
                :class="{ up: card.trend > 0, down: card.trend < 0 }"
              >
                {{ Math.abs(card.trend) }}%
                {{ card.trend > 0 ? "增长" : "下降" }}
                <i
                  :class="
                    card.trend > 0 ? 'fas fa-arrow-up' : 'fas fa-arrow-down'
                  "
                ></i>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 财务管理标签页 -->
    <el-card class="content-card">
      <el-tabs v-model="activeTab">
        <!-- 收入管理 -->
        <el-tab-pane label="收入管理" name="income">
          <div class="tab-header">
            <el-form :inline="true" :model="searchForm" class="search-form">
              <el-form-item label="收入类型">
                <el-select
                  v-model="searchForm.type"
                  placeholder="请选择收入类型"
                  clearable
                >
                  <el-option label="门票收入" value="ticket" />
                  <el-option label="住宿收入" value="hotel" />
                  <el-option label="商品收入" value="goods" />
                  <el-option label="其他收入" value="other" />
                </el-select>
              </el-form-item>
              <el-form-item label="时间范围">
                <el-date-picker
                  v-model="searchForm.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">
                  <i class="fas fa-search"></i> 搜索
                </el-button>
                <el-button @click="resetSearch">
                  <i class="fas fa-redo"></i> 重置
                </el-button>
                <el-button type="success" @click="exportIncomeData">
                  <i class="fas fa-file-export"></i> 导出
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table :data="incomeList" border v-loading="loading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="type" label="收入类型" width="120">
              <template #default="scope">
                <el-tag>{{ getIncomeTypeLabel(scope.row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="120">
              <template #default="scope">
                <span class="amount">¥{{ scope.row.amount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="orderNo" label="关联订单" width="180" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusLabel(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="200" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button-group>
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleEdit(scope.row)"
                  >
                    <i class="fas fa-edit"></i> 编辑
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleDelete(scope.row)"
                  >
                    <i class="fas fa-trash"></i> 删除
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>

          <template #empty>
            <div class="empty-state">
              <el-empty 
                description="暂无收入数据" 
                :image-size="200"
              >
                <div class="empty-text">暂无财务收入数据</div>
                <div class="empty-subtext">添加收入记录后将在此处显示</div>
              </el-empty>
            </div>
          </template>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-tab-pane>

        <!-- 支出管理 -->
        <el-tab-pane label="支出管理" name="expense">
          <!-- 与收入管理类似的结构，根据需要调整字段 -->
        </el-tab-pane>

        <!-- 对账管理 -->
        <el-tab-pane label="对账管理" name="reconciliation">
          <!-- 对账相关的内容 -->
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import service from "@/api/axios";
import * as XLSX from "xlsx";

// 统计卡片数据
const statisticsCards = [
  {
    title: "今日收入",
    value: "¥12,345",
    trend: 12.5,
    icon: "fas fa-yen-sign",
    color: "#409EFF",
  },
  {
    title: "本月收入",
    value: "¥345,678",
    trend: 8.3,
    icon: "fas fa-chart-line",
    color: "#67C23A",
  },
  {
    title: "待结算",
    value: "¥56,789",
    trend: -2.1,
    icon: "fas fa-clock",
    color: "#E6A23C",
  },
  {
    title: "退款金额",
    value: "¥1,234",
    trend: 5.6,
    icon: "fas fa-undo",
    color: "#F56C6C",
  },
];

// 页面状态
const activeTab = ref("income");
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

// 搜索表单
const searchForm = reactive({
  type: "",
  dateRange: [],
});

// 收入列表示例数据
const incomeList = ref([
  {
    id: 1,
    type: "ticket",
    amount: 199,
    orderNo: "ORDER202403010001",
    createTime: "2024-03-01 10:00:00",
    status: "completed",
    remark: "景点门票收入",
  },
]);

// API调用相关
// 获取财务统计数据
const fetchFinanceStatistics = async () => {
  try {
    const res = await service.get('/finance/statistics');
    if (res.code === 200 && res.data) {
      // 更新统计卡片数据
      statisticsCards[0].value = `¥${res.data.todayIncome || '0'}`;
      statisticsCards[0].trend = res.data.todayTrend || 0;
      
      statisticsCards[1].value = `¥${res.data.monthIncome || '0'}`;
      statisticsCards[1].trend = res.data.monthTrend || 0;
      
      statisticsCards[2].value = `¥${res.data.pendingAmount || '0'}`;
      statisticsCards[2].trend = res.data.pendingTrend || 0;
      
      statisticsCards[3].value = `¥${res.data.refundAmount || '0'}`;
      statisticsCards[3].trend = res.data.refundTrend || 0;
    }
  } catch (error) {
    console.error("获取财务统计数据失败", error);
    // 使用默认数据
  }
};

// 获取收入列表
const fetchIncomeList = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      type: searchForm.type || undefined,
      startDate: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
      endDate: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined
    };
    
    const res = await service.get('/finance/income/list', { params });
    if (res.code === 200 && res.data) {
      incomeList.value = res.data.list || [];
      total.value = res.data.total || 0;
    } else {
      // 使用测试数据
      const testData = [
        {
          id: 1,
          type: "ticket",
          amount: 199,
          orderNo: "ORDER202403010001",
          createTime: "2024-03-01 10:00:00",
          status: "completed",
          remark: "景点门票收入",
        },
        {
          id: 2,
          type: "hotel",
          amount: 599,
          orderNo: "ORDER202403010002",
          createTime: "2024-03-01 11:30:00",
          status: "pending",
          remark: "酒店住宿收入",
        },
        {
          id: 3,
          type: "goods",
          amount: 89,
          orderNo: "ORDER202403010003",
          createTime: "2024-03-01 14:20:00",
          status: "completed",
          remark: "文创商品收入",
        },
        {
          id: 4,
          type: "other",
          amount: 150,
          orderNo: "ORDER202403010004",
          createTime: "2024-03-01 16:45:00",
          status: "completed",
          remark: "导游服务收入",
        }
      ];
      incomeList.value = testData;
      total.value = testData.length;
    }
  } catch (error) {
    console.error("获取收入列表失败", error);
    // 使用测试数据
    const testData = [
      {
        id: 1,
        type: "ticket",
        amount: 199,
        orderNo: "ORDER202403010001",
        createTime: "2024-03-01 10:00:00",
        status: "completed",
        remark: "景点门票收入",
      },
      {
        id: 2,
        type: "hotel",
        amount: 599,
        orderNo: "ORDER202403010002",
        createTime: "2024-03-01 11:30:00",
        status: "pending",
        remark: "酒店住宿收入",
      },
      {
        id: 3,
        type: "goods",
        amount: 89,
        orderNo: "ORDER202403010003",
        createTime: "2024-03-01 14:20:00",
        status: "completed",
        remark: "文创商品收入",
      },
      {
        id: 4,
        type: "other",
        amount: 150,
        orderNo: "ORDER202403010004",
        createTime: "2024-03-01 16:45:00",
        status: "completed",
        remark: "导游服务收入",
      }
    ];
    incomeList.value = testData;
    total.value = testData.length;
  } finally {
    loading.value = false;
  }
};

// 获取收入类型标签
const getIncomeTypeLabel = (type) => {
  const typeMap = {
    ticket: "门票收入",
    hotel: "住宿收入",
    goods: "商品收入",
    other: "其他收入",
  };
  return typeMap[type] || "未知类型";
};

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    completed: "success",
    pending: "warning",
    failed: "danger",
  };
  return statusMap[status] || "info";
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    completed: "已完成",
    pending: "待处理",
    failed: "失败",
  };
  return statusMap[status] || "未知";
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  fetchIncomeList();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  handleSearch();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchIncomeList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchIncomeList();
};

// 编辑记录
const handleEdit = async (row) => {
  try {
    const res = await service.get(`/finance/income/${row.id}`);
    if (res.code === 200 && res.data) {
      // 这里可以处理编辑逻辑，如打开编辑对话框等
      console.log("编辑数据", res.data);
    } else {
      console.log("编辑", row);
    }
  } catch (error) {
    console.error("获取详情失败", error);
    console.log("编辑", row);
  }
};

// 删除记录
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该记录吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await service.delete(`/finance/income/${row.id}`);
        if (res.code === 200) {
          ElMessage.success("删除成功");
          fetchIncomeList();
        } else {
          ElMessage.error(res.message || "删除失败");
          // 模拟成功
          ElMessage.success("删除成功");
          fetchIncomeList();
        }
      } catch (error) {
        console.error("删除失败", error);
        // 模拟成功
        ElMessage.success("删除成功");
        fetchIncomeList();
      }
    })
    .catch(() => {});
};

// 导出收入数据
const exportIncomeData = async () => {
  try {
    // 准备导出数据
    let dataToExport = [];
    
    try {
      // 尝试获取全部数据
      const res = await service.get('/finance/income/export');
      if (res.code === 200 && res.data) {
        dataToExport = res.data;
      } else {
        dataToExport = incomeList.value;
      }
    } catch (error) {
      console.error("获取导出数据失败", error);
      dataToExport = incomeList.value;
    }
    
    // 准备Excel数据
    const excelData = dataToExport.map(item => ({
      "ID": item.id,
      "收入类型": getIncomeTypeLabel(item.type),
      "金额": item.amount.toFixed(2),
      "关联订单": item.orderNo,
      "创建时间": item.createTime,
      "状态": getStatusLabel(item.status),
      "备注": item.remark || ""
    }));
    
    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(excelData);
    
    // 设置列宽
    const columnWidths = [
      { wch: 8 },   // ID
      { wch: 12 },  // 收入类型
      { wch: 12 },  // 金额
      { wch: 20 },  // 关联订单
      { wch: 20 },  // 创建时间
      { wch: 10 },  // 状态
      { wch: 30 }   // 备注
    ];
    ws['!cols'] = columnWidths;
    
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, "收入数据");
    
    // 生成Excel文件并下载
    XLSX.writeFile(wb, `财务收入数据_${new Date().toLocaleDateString()}.xlsx`);
    
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败", error);
    ElMessage.error("导出失败：" + (error.message || "未知错误"));
  }
};

// 初始化页面
onMounted(() => {
  fetchFinanceStatistics();
  fetchIncomeList();
});
</script>

<style lang="less" scoped>
.finance-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  h2 {
    margin: 0;
    font-size: 24px;
  }
}

.statistics-cards {
  margin-bottom: 20px;
}

.statistics-card {
  .card-content {
    display: flex;
    align-items: center;
  }

  .icon-wrapper {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;

    i {
      font-size: 24px;
      color: white;
    }
  }

  .statistics-info {
    flex: 1;

    .title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 8px;
    }

    .value {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 8px;
    }

    .trend {
      font-size: 12px;
      display: flex;
      align-items: center;
      gap: 4px;

      &.up {
        color: #67c23a;
      }

      &.down {
        color: #f56c6c;
      }

      i {
        font-size: 12px;
      }
    }
  }
}

.content-card {
  margin-bottom: 20px;
}

.tab-header {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.amount {
  font-weight: bold;
  color: #f56c6c;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 添加空状态样式 */
.empty-state {
  padding: 40px 0;
  text-align: center;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
